import React from 'react';
import * as echarts from 'echarts';
import Thumb from './Thumb';
import styles from './index.less';

export default (props) => {
  const {
    option = null,
    mark = [],
    onChangeStartIndex = () => {},
    hoverColIndex = 0,
    pageSize = 0,
    total = 0,
    pageWidth = 0,
  } = props;
  const chartRef = React.useRef(null);
  const scrollRef = React.useRef(null);

  let [left, setLeft] = React.useState(0);
  let [cellWidth, setCellWidth] = React.useState(0);
  let [thumbWidth, setThumbWidth] = React.useState(0);
  let [totalWidth, setTotalWidth] = React.useState(0);
  let [scrollLeft, setScrollLeft] = React.useState(0);
  const chartIns = () =>
    echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);

  const chartResize = () => {
    setTimeout(() => {
      chartIns()?.resize();
    }, 500);
  };

  React.useEffect(() => {
    return () => {
      chartIns()?.dispose();
    };
  }, [chartRef]);

  React.useEffect(() => {
    if (!option) return;
    chartIns()?.setOption(option, true);
  }, [JSON.stringify(option)]);

  React.useEffect(() => {
    resetWidth();
    setTimeout(() => {
      initWidth();
    }, 0);
    chartResize();
  }, [pageWidth, pageSize, total]);

  React.useEffect(() => {
    chartIns()?.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: hoverColIndex,
    });
  }, [hoverColIndex]);

  React.useEffect(() => {
    const v = left + scrollLeft;
    let i;
    if (totalWidth && v + thumbWidth > totalWidth) {
      i = total - 1;
    } else {
      i = Math.round(v / cellWidth);
    }
    if (isNaN(i)) i = 0;
    onChangeStartIndex(i);
  }, [left]);

  const resetWidth = () => {
    setLeft(0);
    setCellWidth(0);
    setThumbWidth(0);
    setTotalWidth(0);
    setScrollLeft(0);
  };

  const initWidth = () => {
    if (!pageWidth || !total) return;
    const cellMin = 10; // 列最小宽度
    let cellWidth = 0;
    if (total * cellMin > pageWidth) {
      cellWidth = 10;
      totalWidth = total * cellMin;
      thumbWidth = (pageSize / total) * totalWidth;
    } else {
      totalWidth = 0;
      if (pageSize === total) {
        thumbWidth = 0;
      } else {
        cellWidth = pageWidth / total;
        thumbWidth = (pageSize / total) * pageWidth;
      }
    }
    setCellWidth(cellWidth);
    setThumbWidth(thumbWidth);
    setTotalWidth(totalWidth);
    setScrollLeft(0);
    chartResize();
  };

  const changeZoom = (n) => {
    if (n > 0) {
      scrollLeft += pageWidth;
      if (scrollLeft > totalWidth - pageWidth) {
        scrollLeft = totalWidth - pageWidth;
      }
    } else {
      scrollLeft -= pageWidth;
      if (scrollLeft < 0) scrollLeft = 0;
    }
    setScrollLeft(scrollLeft);
    scrollRef.current.scrollLeft = scrollLeft;
  };

  const _renderThumb = () => {
    if (!thumbWidth) return null;
    return (
      <>
        {scrollLeft > 0 && (
          <div
            className={styles.arrow_left}
            onClick={(e) => {
              e.stopPropagation();
              changeZoom(-1);
            }}
          />
        )}
        {scrollLeft + pageWidth < totalWidth && (
          <div
            className={styles.arrow_right}
            onClick={(e) => {
              e.stopPropagation();
              changeZoom(1);
            }}
          />
        )}
        <Thumb pageWidth={pageWidth} thumbWidth={thumbWidth} onLeft={setLeft} />
      </>
    );
  };
  return (
    <div className={styles.chart_zoom}>
      <div className={styles.chart_zoom__scroll} ref={scrollRef}>
        <div style={{ width: totalWidth || '100%' }}>
          <div className={styles.chart_zoom__nav}>
            {mark?.map((x) => (
              <div key={x}>{x}</div>
            ))}
          </div>
          <div ref={chartRef} className={styles.chart_zoom__chart} />
        </div>
      </div>
      <div className={styles.chart_zoom__theme}>{_renderThumb()}</div>
    </div>
  );
};
